package Thread.Safe;

/**
 * synchronize修饰同步代码块
 */
public class synchronize_codeblock {
    public static void main(String[] args) {
        Counter counter1=new Counter();
        Counter counter2=new Counter();
        Counter counter3=new Counter();
        Thread t1=new Thread(()->{
            counter1.increase();
        },"t1线程~~");
        Thread t2=new Thread(()->{
            counter2.increase();
        },"t2线程~~");
        Thread t3=new Thread(()->{
            counter3.increase();
        },"t3线程~~");
        t1.start();
        t2.start();
        t3.start();
    }

    private static class Counter{
    public void increase() {
        System.out.println("张三");
        System.out.println("李四");
        System.out.println("王麻子");

        //若锁的是class对象，全局唯一
        synchronized (Counter.class) {
            while (true) {
                System.out.println(Thread.currentThread().getName() + "获取到锁~~");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        //同步代码快，进入同步代码快，获取到指定的锁
        //this表示当前对象的引用，锁的就是当前对象
//        synchronized (this) {
//            while (true) {
//                System.out.println(Thread.currentThread().getName() + "获取到锁~~");
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//            }
//        }

}
}
}